<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket</title>
</head>
<body>
<h1>Echo Test</h1>
<input id="sendTxt" type="text" />
<button id="sendBtn">发送</button>
<div id="recv"></div>
<script type="text/javascript">

    //创建一个webSocket实例，执行后，客户端就会与服务端连接
    // let websocket = new WebSocket("ws://82.157.123.54:9010/ajaxchattest");
    userId =Date.now()
    let websocket = new WebSocket("ws://localhost:8081/websocket/"+userId.toString().substring(userId.toString().length-3));
    //当WebSocket创建成功时，触发onopen事件
    websocket.onopen = function () {

        console.log('websocket open');
        document.getElementById("recv").innerText = "链接成功";
    }
    //当客户端收到服务端发送的关闭连接请求时，触发onclose事件
    websocket.onclose = function () {

        console.log('websocket close');
    }
    //当客户端收到服务端发来的消息时，触发onmessage事件
    websocket.onmessage = function (ev) {
        //e.data 的数据格式也是字符串，手动解析这些数据才能得到其他格式的数据。
        // const _data = JSON.parse(ev.data);
        // console.log(ev.data,_data);
        console.log(ev.data);

        document.getElementById("recv").innerHTML = ev.data;
    }

    document.getElementById("sendBtn").onclick = function () {

        let txt = document.getElementById("sendTxt").value;
        console.log(txt);
        websocket.send(txt);
    }

</script>
</body>
</html>